package com.example.chat.service;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.aliyun.mns.common.ClientException;
import com.aliyuncs.dysmsapi.model.v20170525.QuerySendDetailsResponse;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.chat.beans.*;
import com.example.chat.mapper.*;
import com.example.chat.result.*;
import com.example.chat.utils.*;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.UUID;

@Service
public class AdminService extends ServiceImpl<AdminMapper, Admin> {

    @Value("${global.config.path}")
    String configPath;
    @Value("${global.config.website}")
    String website;
    @Resource
    TokenMapper tokenMapper;
    @Resource
    CheckUtils checkUtils;
    @Resource
    Global global;
    @Resource
    CodeMapper codeMapper;
    @Resource
    RoleRelMapper roleRelMapper;
    @Resource
    MateMapper mateMapper;
    @Resource
    RecordMapper recordMapper;
    @Resource
    private PointRecordService pointRecordService;
    @Resource
    private PointWithdrawalService pointWithdrawalsService;

    public ApiResult<LoginResult> login(String username, String password, HttpServletRequest request, Integer type) {
        ApiResult<LoginResult> result = new ApiResult<>();
        int status = 0;
        String msg = "登录出错";
        try {
            Admin admin = baseMapper.selectByUsername(username);
            if (admin != null) {
                if (admin.getType() == type) {
                    if (admin.getBlacklist() == 2) {
                        if (admin.getPassword().equals(DigestUtils.md5DigestAsHex(password.getBytes(StandardCharsets.UTF_8)))) {
                            String strToken = UUID.randomUUID().toString();

                            long time = System.currentTimeMillis();
                            Token token = new Token();
                            token.setToken(strToken);
                            token.setAdminId(admin.getId());
                            token.setLastTime(time);
                            tokenMapper.insert(token);

                            admin.setIp(IpUtil.getIpAddr(request));
                            admin.setLoginTime(System.currentTimeMillis());
                            // 计算积分
                            pointRecordService.loginPoint(admin);
                            baseMapper.updateById(admin);

                            LoginResult loginResult = new LoginResult(admin.getPermission().size() > 0 ? Arrays.asList(admin.getPermission().get(0).split(",")) : new ArrayList<>(), admin.getUid(), strToken, admin.getId());
                            status = 1;
                            msg = "登录成功";
                            result.setData(loginResult);
                        } else
                            msg = "密码错误";
                    } else
                        msg = "您已被拉入黑名单，无法登录";
                } else
                    msg = "登录用户类型错误";
            } else
                msg = "用户名错误";
        } catch (Exception e) {
            e.printStackTrace();
        }
        result.setStatus(status);
        result.setMsg(msg);
        return result;
    }

    public ApiResult<Base> exit(Integer userId, String token) {
        ApiResult<Base> apiResult = checkUtils.checkToken(Arrays.asList(userId, token), userId, token, "");
        if (apiResult.getStatus() != 1)
            return new ApiResult<>(apiResult.getStatus(), apiResult.getMsg(), null);
        ApiResult<Base> result = new ApiResult<>();
        int status = 0;
        String msg = "退出失败";
        try {
            Admin admin = baseMapper.selectById(userId);
            if (admin != null) {
                baseMapper.updateById(admin);
                tokenMapper.deleteByAdminIdAndToken(userId, token);
                status = 1;
                msg = "退出成功";
            } else
                msg = "用户不存在";

        } catch (Exception e) {
            e.printStackTrace();
        }
        result.setStatus(status);
        result.setMsg(msg);
        return result;
    }

    public ApiResult<String> upload(MultipartFile file, HttpServletRequest request, int type) {
        ApiResult<String> result = new ApiResult<>();
        int status = 0;
        String msg = "上传失败";
        try {
            InputStream inputStream;
            String typeName = "";
            String fileName = file.getOriginalFilename().replace("\\", "_");
            List<String> sub = new ArrayList<>();
            if (type == 1) {
                typeName = "photo";
                sub = global.getSuffixPhoto();
            }
            if (type == 2) {
                typeName = "html";
                sub = global.getSuffixFile();
            }
            if (sub.contains(fileName.substring(fileName.lastIndexOf(".") + 1))) {
                try {
                    inputStream = file.getInputStream();
                    String path = FileHandleUtil.upload(inputStream,
                            System.currentTimeMillis()
                                    + "_"
                                    + global.getPackNum()
                                    + "."
                                    + fileName.substring(fileName.lastIndexOf(".") + 1), configPath, typeName, true);
                    result.setData(path);
                    status = 1;
                    msg = "上传成功";
                    global.setPackNum(global.getPackNum() + 1);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            } else {
                msg = "无法上传该类型文件";
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        result.setStatus(status);
        result.setMsg(msg);
        return result;
    }

    public ApiResult<Base> sendCode(String tel, Integer type) {
        ApiResult<Base> result = new ApiResult<>();
        int status = 0;
        String msg = "验证码发送失败";
        if (type != 0 && !tel.equals("")) {
            try {
                String strCode = Global.getRandom();
                String title = "", content = "";
                Code code = codeMapper.selectByTel(tel);
                if (code == null) {
                    code = new Code();
                    code.setTel(tel);
                }
                code.setType(type);
                code.setCode(strCode);
//                code.setCode("666666");
                code.setLastTime(System.currentTimeMillis() + 300000);
                if (code.getId() == null)
                    codeMapper.insert(code);
                else
                    codeMapper.updateById(code);

                // 发验证码短信
                SendSmsResponse response = null;
                try {
                    if (type == 1)
                        response = SmsUtil.sendVerifyCode(tel, strCode, global.getConfig().getAliyunCode(),global.getConfig().getAliyunSign());
                    if (type == 2)
                        response = SmsUtil.sendVerifyCode(tel, strCode, "SMS_160270385",global.getConfig().getAliyunSign());
                } catch (ClientException e) {
                    e.printStackTrace();
                }
                System.out.println("短信接口返回的数据----------------");
                System.out.println("Code=" + response.getCode());
                System.out.println("Message=" + response.toString());
                System.out.println("RequestId=" + response.getRequestId());
                System.out.println("BizId=" + response.getBizId());//消息回执id

                // 查明细
                if (response.getCode() != null && response.getCode().equals("OK")) {
                    QuerySendDetailsResponse querySendDetailsResponse = null;
                    try {
                        querySendDetailsResponse = SmsUtil.querySendDetails(tel, response.getBizId());
                    } catch (ClientException e) {
                        e.printStackTrace();
                    }
                    System.out.println("短信明细查询接口返回数据----------------");
                    System.out.println("Code=" + querySendDetailsResponse.getCode());
                    System.out.println("Message=" + querySendDetailsResponse.toString());
                    int i = 0;
                    for (QuerySendDetailsResponse.SmsSendDetailDTO smsSendDetailDTO : querySendDetailsResponse
                            .getSmsSendDetailDTOs()) {
                        System.out.println("SmsSendDetailDTO[" + i + "]:");
                        System.out.println("Content=" + smsSendDetailDTO.getContent());
                        System.out.println("ErrCode=" + smsSendDetailDTO.getErrCode());
                        System.out.println("OutId=" + smsSendDetailDTO.getOutId());
                        System.out.println("PhoneNum=" + smsSendDetailDTO.getPhoneNum());
                        System.out.println("ReceiveDate=" + smsSendDetailDTO.getReceiveDate());
                        System.out.println("SendDate=" + smsSendDetailDTO.getSendDate());
                        System.out.println("SendStatus=" + smsSendDetailDTO.getSendStatus());
                        System.out.println("Template=" + smsSendDetailDTO.getTemplateCode());
                    }
                    System.out.println("TotalCount=" + querySendDetailsResponse.getTotalCount());
                    System.out.println("RequestId=" + querySendDetailsResponse.getRequestId());
                    msg = "发送成功";
                    status = 1;
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        } else {
            msg = "参数不全";
        }
        result.setStatus(status);
        result.setMsg(msg);
        return result;
    }

    public ApiResult<Base> forgetPasswordCode(String tel, String code) {
        ApiResult<Base> result = new ApiResult<>();
        int status = 0;
        String msg = "手机验证失败";
        try {
            Admin admin = baseMapper.selectByUsername(tel);
            if (admin != null) {
                Code target = codeMapper.selectByTel(tel);
                if (target != null) {
                    if (target.getLastTime() > System.currentTimeMillis()) {
                        if (target.getType() == 2) {
                            if (target.getCode().equals(code)) {
                                status = 1;
                                msg = "验证成功";
                            } else {
                                msg = "验证码错误,请重新输入";
                            }
                        } else {
                            msg = "验证码类型错误";
                        }
                    } else {
                        msg = "验证码已过期";
                    }
                } else {
                    msg = "验证码还未发送";
                }
            } else {
                msg = "该手机还未注册";
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        result.setStatus(status);
        result.setMsg(msg);
        return result;
    }

    public ApiResult<Base> forgetPasswordReset(String tel, String password, String code) {
        ApiResult<Base> result = new ApiResult<>();
        int status = 0;
        String msg = "密码重置失败";
        try {
            Admin admin = baseMapper.selectByUsername(tel);
            if (admin != null) {
                Code target = codeMapper.selectByTel(tel);
                if (target != null) {
                    if (code.equals(target.getCode())) {
                        admin.setPassword(DigestUtils.md5DigestAsHex(password.getBytes(StandardCharsets.UTF_8)));
                        baseMapper.updateById(admin);

                        target.setLastTime(System.currentTimeMillis());
                        codeMapper.updateById(target);
                        status = 1;
                        msg = "密码重置成功";
                    } else {
                        msg = "验证码错误,请重新输入";
                    }
                } else {
                    msg = "验证码还未发送";
                }
            } else {
                msg = "该手机还未注册";
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        result.setStatus(status);
        result.setMsg(msg);
        return result;
    }

    public ApiResult<Base> register(String tel, String password, String code) {
        ApiResult<Base> result = new ApiResult<>();
        int status = 0;
        String msg = "注册失败";
        try {
            Admin admin = baseMapper.selectByUsername(tel);
            if (admin == null) {
                Code target = codeMapper.selectByTel(tel);
                if (target != null) {
                    if (target.getLastTime() > System.currentTimeMillis()) {
                        if (target.getType() == 1) {
                            if (target.getCode().equals(code)) {
                                admin = new Admin();
                                admin.setUsername(tel);
                                admin.setPassword(DigestUtils.md5DigestAsHex(password.getBytes(StandardCharsets.UTF_8)));
                                admin.setTel(tel);
                                admin.setCreateTime(System.currentTimeMillis());
                                admin.setType(1);
                                baseMapper.insert(admin);

                                RoleRel roleRel = new RoleRel();
                                roleRel.setRoleId(2);
                                roleRel.setAdminId(admin.getId());
                                roleRel.setCreateAdmin(admin.getId());
                                roleRel.setCreateTime(System.currentTimeMillis());
                                roleRelMapper.insert(roleRel);

                                target.setLastTime(System.currentTimeMillis());
                                codeMapper.updateById(target);
                                status = 1;
                                msg = "注册成功";
                            } else {
                                msg = "验证码错误,请重新输入";
                            }
                        } else {
                            msg = "验证码类型错误";
                        }
                    } else {
                        msg = "验证码已过期";
                    }
                } else {
                    msg = "验证码还未发送";
                }
            } else {
                msg = "该手机已被注册";
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        result.setStatus(status);
        result.setMsg(msg);
        return result;
    }

    public ListResult<List<AdminResult>> listAdmin(Integer userId, String token, String tel, int type, Integer page, Integer limit) {
        ApiResult<Base> apiResult = checkUtils.checkToken(Arrays.asList(userId, token), userId, token, "1001");
        if (apiResult.getStatus() != 1)
            return new ListResult<>(apiResult.getStatus(), apiResult.getMsg(), null, 0, 0, 0);
        ListResult<List<AdminResult>> result = new ListResult<>();
        int status = 0;
        String msg = "获取失败";
        try {
            Page<Admin> pages = new Page<>(page, limit);
            IPage<Admin> iPages = baseMapper.selectBySearchAdmin(pages, tel, type);
            List<AdminResult> adminResults = new ArrayList<>();
            for (Admin admin : iPages.getRecords()) {
                AdminResult adminResult = new AdminResult();
                adminResult.setId(admin.getId());
                adminResult.setUsername(admin.getUsername());
                adminResult.setNickName(admin.getNickName());
                adminResult.setTel(admin.getTel());
                adminResult.setEmail(admin.getEmail());
                adminResult.setBlacklist(admin.getBlacklist());
                adminResult.setType(admin.getType());
                adminResult.setIcon(admin.getIcon());
                adminResult.setIconFullPath(admin.getIcon().equals("") ? "" : website + admin.getIcon());
                adminResult.setCreateTime(Global.longToString(admin.getCreateTime()));
                adminResult.setCreateAdmin(admin.getCreateAdminName());
                adminResult.setLoginTime(Global.longToString(admin.getLoginTime()));
                adminResult.setRecordTime(Global.longToString(admin.getRecordTime()));
                adminResult.setUid(admin.getUid());
                adminResult.setTimes(admin.getTimes());
                adminResult.setOrderType(admin.getOrderType());
                adminResult.setPoint(admin.getPoint());
                adminResults.add(adminResult);
            }
            result.setData(adminResults);
            result.setPage(page);
            result.setLimit(limit);
            result.setTotal(iPages.getTotal());
            msg = "获取成功";
            status = 1;
        } catch (Exception e) {
            e.printStackTrace();
        }
        result.setStatus(status);
        result.setMsg(msg);
        return result;
    }

    public ApiResult<Base> addAdmin(Integer userId, String token, String username, String password, String tel, String email, String icon, String nickName, Integer type) {
        ApiResult<Base> apiResult = checkUtils.checkToken(Arrays.asList(userId, token, username, nickName), userId, token, "1002");
        if (apiResult.getStatus() != 1)
            return new ApiResult<>(apiResult.getStatus(), apiResult.getMsg(), null);
        ApiResult<Base> result = new ApiResult<>();
        int status = 0;
        String msg = "创建失败";
        try {
            Admin admin = baseMapper.selectByUsername(username);
            if (admin == null) {
                admin = new Admin();
                admin.setUsername(username);
                admin.setNickName(nickName);
                admin.setPassword(DigestUtils.md5DigestAsHex(password.getBytes(StandardCharsets.UTF_8)));
                admin.setCreateAdmin(userId);
                admin.setCreateTime(System.currentTimeMillis());
                admin.setType(type);
                admin.setTel(tel);
                admin.setEmail(email);
                admin.setIcon(icon);
                baseMapper.insert(admin);

                RoleRel roleRel = new RoleRel();
                roleRel.setRoleId(1);
                roleRel.setAdminId(admin.getId());
                roleRel.setCreateAdmin(userId);
                roleRel.setCreateTime(System.currentTimeMillis());
                roleRelMapper.insert(roleRel);

                msg = "创建成功";
                status = 1;
            } else msg = "用户名已被使用";
        } catch (Exception e) {
            e.printStackTrace();
        }
        result.setStatus(status);
        result.setMsg(msg);
        return result;
    }

    public ApiResult<Base> editAdmin(Integer userId, String token, Integer ids, String nickName, String tel, String email, String icon, String password) {
        String permission = "1003";
        if (userId.equals(ids)) {
            permission = "";
        }
        ApiResult<Base> apiResult = checkUtils.checkToken(Arrays.asList(userId, token, ids, nickName, tel), userId, token, permission);
        if (apiResult.getStatus() != 1)
            return new ApiResult<>(apiResult.getStatus(), apiResult.getMsg(), null);
        ApiResult<Base> result = new ApiResult<>();
        int status = 0;
        String msg = "更新失败";
        try {
            Admin admin = baseMapper.selectById(ids);
            if (admin != null) {
                admin.setNickName(nickName);
                admin.setTel(tel);
                admin.setEmail(email);
                admin.setIcon(icon);
                if (StringUtils.isNotBlank(password)) {
                    admin.setPassword(DigestUtils.md5DigestAsHex(password.getBytes(StandardCharsets.UTF_8)));
                }
                baseMapper.updateById(admin);
                msg = "更新成功";
                status = 1;
            } else msg = "用户不存在";
        } catch (Exception e) {
            e.printStackTrace();
        }
        result.setStatus(status);
        result.setMsg(msg);
        return result;
    }

    public ApiResult<AdminResult> getAdmin(Integer userId, String token, Integer ids) {
        ApiResult<Base> apiResult = checkUtils.checkToken(Arrays.asList(userId, token), userId, token, "1001");
        if (apiResult.getStatus() != 1)
            return new ApiResult<>(apiResult.getStatus(), apiResult.getMsg(), null);
        ApiResult<AdminResult> result = new ApiResult<>();
        int status = 0;
        String msg = "获取失败";
        try {
            Admin admin = null;
            if (ids != 0)
                admin = baseMapper.selectById(ids);
            if (admin != null) {
                AdminResult adminResult = new AdminResult();
                adminResult.setId(admin.getId());
                adminResult.setUsername(admin.getUsername());
                adminResult.setNickName(admin.getNickName());
                adminResult.setTel(admin.getTel());
                adminResult.setEmail(admin.getEmail());
                adminResult.setBlacklist(admin.getBlacklist());
                adminResult.setType(admin.getType());
                adminResult.setIcon(admin.getIcon());
                adminResult.setIconFullPath(admin.getIcon().equals("") ? "" : website + admin.getIcon());
                adminResult.setCreateTime(Global.longToString(admin.getCreateTime()));
                adminResult.setCreateAdmin(admin.getCreateAdminName());
                adminResult.setLoginTime(Global.longToString(admin.getLoginTime()));
                adminResult.setRecordTime(Global.longToString(admin.getRecordTime()));
                adminResult.setTimes(admin.getTimes());
                adminResult.setUid(admin.getUid());
                adminResult.setPoint(admin.getPoint());
                if (admin.getRecordTime() >= System.currentTimeMillis())
                    adminResult.setOrderType(admin.getOrderType());

                adminResult.setTodayTimes(recordMapper.selectTimesByAdminId(Global.getTodayStartEndTime(1),
                        Global.getTodayStartEndTime(2), userId));
                status = 1;
                msg = "获取成功";
                result.setData(adminResult);
            } else msg = "用户不存在";
        } catch (Exception e) {
            e.printStackTrace();
        }
        result.setStatus(status);
        result.setMsg(msg);
        return result;
    }

    public ApiResult<Base> deleteAdmin(Integer userId, String token, Integer[] ids) {
        ApiResult<Base> apiResult = checkUtils.checkToken(Arrays.asList(userId, token), userId, token, "1004");
        if (apiResult.getStatus() != 1)
            return new ApiResult<>(apiResult.getStatus(), apiResult.getMsg(), null);
        ApiResult<Base> result = new ApiResult<>();
        int status = 0;
        String msg = "删除失败";
        try {
            for (Integer id : ids) {
                Admin admin = baseMapper.selectById(id);
                if (admin == null) {
                    continue;
                }
                baseMapper.deleteById(id);
            }
            msg = "删除成功";
            status = 1;
        } catch (Exception e) {
            e.printStackTrace();
        }
        result.setStatus(status);
        result.setMsg(msg);
        return result;
    }

    public ApiResult<List<AdminResult>> allAdmin(Integer userId, String token) {
        ApiResult<Base> apiResult = checkUtils.checkToken(Arrays.asList(userId, token), userId, token, "1001");
        if (apiResult.getStatus() != 1)
            return new ApiResult<>(apiResult.getStatus(), apiResult.getMsg(), null);
        ApiResult<List<AdminResult>> result = new ApiResult<>();
        int status = 0;
        String msg = "获取失败";
        try {
            List<Admin> list = baseMapper.allAdmin();
            List<AdminResult> adminResults = new ArrayList<>();
            for (Admin admin : list) {
                AdminResult adminResult = new AdminResult();
                adminResult.setId(admin.getId());
                adminResult.setUsername(admin.getUsername());
                adminResult.setNickName(admin.getNickName());
                adminResult.setTel(admin.getTel());
                adminResult.setEmail(admin.getEmail());
                adminResult.setBlacklist(admin.getBlacklist());
                adminResult.setType(admin.getType());
                adminResult.setIcon(admin.getIcon());
                adminResult.setIconFullPath(website + admin.getIcon());
                adminResult.setCreateTime(Global.longToString(admin.getCreateTime()));
                adminResult.setCreateAdmin(admin.getCreateAdminName());
                adminResult.setLoginTime(Global.longToString(admin.getLoginTime()));
                adminResult.setRecordTime(Global.longToString(admin.getRecordTime()));
                adminResult.setUid(admin.getUid());
                adminResults.add(adminResult);
            }
            result.setData(adminResults);
            msg = "获取成功";
            status = 1;
        } catch (Exception e) {
            e.printStackTrace();
        }
        result.setStatus(status);
        result.setMsg(msg);
        return result;
    }

    public ApiResult<Base> editAdminUid(Integer userId, String token, Integer ids, String uid) {
        String permission = "1003";
        if (userId.equals(ids)) {
            permission = "";
        }
        ApiResult<Base> apiResult = checkUtils.checkToken(Arrays.asList(userId, token, ids, uid), userId, token, permission);
        if (apiResult.getStatus() != 1)
            return new ApiResult<>(apiResult.getStatus(), apiResult.getMsg(), null);
        ApiResult<Base> result = new ApiResult<>();
        int status = 0;
        String msg = "更新失败";
        try {
            Admin admin = baseMapper.selectById(ids);
            if (admin != null) {
                admin.setUid(uid);
                baseMapper.updateById(admin);
                msg = "更新成功";
                status = 1;
            } else msg = "用户不存在";
        } catch (Exception e) {
            e.printStackTrace();
        }
        result.setStatus(status);
        result.setMsg(msg);
        return result;
    }

    public ApiResult<String> uploadScreen(Integer userId, String uuid, Integer mateId, MultipartFile file, HttpServletRequest request) {
        ApiResult<String> result = new ApiResult<>();
        int status = 0;
        String msg = "上传失败";
        try {
            Mate mate = mateMapper.selectById(mateId);
            if (mate != null) {
                InputStream inputStream;
                String typeName = "screen";
                String fileName = file.getOriginalFilename().replace("\\", "_");
                List<String> sub = new ArrayList<>();
                sub = global.getSuffixPhoto();
                String id = "";
                if (uuid.equals(""))
                    id = String.valueOf(userId);
                else
                    id = uuid;
                if (sub.contains(fileName.substring(fileName.lastIndexOf(".") + 1))) {
                    try {
                        inputStream = file.getInputStream();
                        String path = FileHandleUtil.upload(inputStream,
                                id + "_" + System.currentTimeMillis()
                                        + "."
                                        + fileName.substring(fileName.lastIndexOf(".") + 1), configPath, typeName, false);
                        result.setData(path);

                        JSONArray jsonArray = new JSONArray();
                        if (!mate.getScreenList().equals(""))
                            jsonArray = JSONArray.parseArray(mate.getScreenList());
                        if (jsonArray.size() > 0) {
                            List<String> list = new ArrayList<>();
                            for (int i = 0; i < jsonArray.size(); i++) {
                                JSONObject jsonObject = jsonArray.getJSONObject(i);
                                if (jsonObject.getString("id").equals(id)) {
                                    jsonObject.put("path", path);
                                    jsonArray.set(i, jsonObject);
                                    break;
                                } else {
                                    list.add(jsonObject.getString("id"));
                                }
                            }
                            if (!list.contains(id)) {
                                JSONObject jsonObject = new JSONObject();
                                jsonObject.put("id", id);
                                jsonObject.put("path", path);
                                jsonArray.add(jsonObject);
                            }
                        } else {
                            JSONObject jsonObject = new JSONObject();
                            jsonObject.put("id", id);
                            jsonObject.put("path", path);
                            jsonArray.add(jsonObject);
                        }
                        mate.setScreenList(jsonArray.toString());
                        mateMapper.updateById(mate);
                        status = 1;
                        msg = "上传成功";
//                        global.setPackNum(global.getPackNum() + 1);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                } else {
                    msg = "无法上传该类型文件";
                }
            } else msg = "匹配不存在";
        } catch (Exception e) {
            e.printStackTrace();
        }
        result.setStatus(status);
        result.setMsg(msg);
        return result;
    }

    public ApiResult<String> getIcon(Integer userId, MultipartFile file, HttpServletRequest request) {
        ApiResult<String> result = new ApiResult<>();
        int status = 0;
        String msg = "获取失败";
        try {
            Admin admin = baseMapper.selectById(userId);
            if (admin != null) {
                result.setData(admin.getIcon().equals("") ? "" : global.getWebsite() + admin.getIcon());
                status = 1;
                msg = "获取成功";
            } else msg = "用户不存在";
        } catch (Exception e) {
            e.printStackTrace();
        }
        result.setStatus(status);
        result.setMsg(msg);
        return result;
    }

    public ApiResult<String> getScreenshot(Integer userId, String uuid, Integer mateId, HttpServletRequest request) {
        ApiResult<String> result = new ApiResult<>();
        int status = 0;
        String msg = "获取失败";
        try {
            Mate mate = mateMapper.selectById(mateId);
            if (mate != null) {
                Admin admin = null;
                String id = "";
                if (uuid.equals("")) {
                    id = String.valueOf(userId);
                    admin = baseMapper.selectById(userId);
                } else {
                    id = uuid;
                }
                if (mate.getScreenList().equals("") && admin != null) {
                    result.setData(website + admin.getIcon());
                }
                if (!mate.getScreenList().equals("")) {
                    JSONArray jsonArray = JSONArray.parseArray(mate.getScreenList());
                    for (int i = 0; i < jsonArray.size(); i++) {
                        JSONObject jsonObject = jsonArray.getJSONObject(i);
                        if (jsonObject.getString("id").equals(id)) {
                            result.setData(website + jsonObject.getString("path"));
                            break;
                        }
                    }
                    if (result.getData() == null && admin != null) {
                        result.setData(website + admin.getIcon());
                    }
                }
                status = 1;
                msg = "获取成功";
            } else msg = "匹配不存在";
        } catch (Exception e) {
            e.printStackTrace();
        }
        result.setStatus(status);
        result.setMsg(msg);
        return result;
    }

    public ApiResult<Base> blackAdmin(Integer userId, String token, Integer ids, Integer blackList) {
        String permission = "1003";
        if (userId.equals(ids)) {
            permission = "";
        }
        ApiResult<Base> apiResult = checkUtils.checkToken(Arrays.asList(userId, token, ids, blackList), userId, token, permission);
        if (apiResult.getStatus() != 1)
            return new ApiResult<>(apiResult.getStatus(), apiResult.getMsg(), null);
        ApiResult<Base> result = new ApiResult<>();
        int status = 0;
        String msg = "更新失败";
        try {
            Admin admin = baseMapper.selectById(ids);
            if (admin != null) {
                admin.setBlacklist(blackList);
                baseMapper.updateById(admin);
                msg = "更新成功";
                status = 1;
            } else msg = "用户不存在";
        } catch (Exception e) {
            e.printStackTrace();
        }
        result.setStatus(status);
        result.setMsg(msg);
        return result;
    }

    public ApiResult<Boolean> getVersion(String version) {
        ApiResult<Boolean> result = new ApiResult<>();
        int status = 0;
        String msg = "获取失败";
        try {
            Config config = global.getConfig();
            if (config.getVersion().equals(version)) {
                result.setData(true);
            } else
                result.setData(false);
            msg = "获取成功";
            status = 1;
        } catch (Exception e) {
            e.printStackTrace();
        }
        result.setStatus(status);
        result.setMsg(msg);
        return result;
    }
    public ApiResult<String> getNewVersion() {
        ApiResult<String> result = new ApiResult<>();
        int status = 0;
        String msg = "获取失败";
        try {
            Config config = global.getConfig();
            result.setData(config.getVersion());
            msg = "获取成功";
            status = 1;
        } catch (Exception e) {
            e.printStackTrace();
        }
        result.setStatus(status);
        result.setMsg(msg);
        return result;
    }

    public void updateBySuccessPay(Admin admin, String subject) {
        switch (subject) {
            case "视频按次收费":
                admin.setOrderType(0);
                admin.setTimes(admin.getTimes() + 20);
                break;
            case "视频包月收费":
                if (admin.getRecordTime() < System.currentTimeMillis())
                    admin.setOrderType(1);
                if (admin.getRecordTime() == 0)
                    admin.setRecordTime(System.currentTimeMillis() + 2592000000L);
                else {
                    if (admin.getRecordTime() < System.currentTimeMillis())
                        admin.setRecordTime(System.currentTimeMillis() + 2592000000L);
                    else
                        admin.setRecordTime(admin.getRecordTime() + 2592000000L);
                }
                break;
            case "视频包年收费":
                admin.setOrderType(2);
                if (admin.getRecordTime() == 0)
                    admin.setRecordTime(System.currentTimeMillis() + 31536000000L);
                else {
                    if (admin.getRecordTime() < System.currentTimeMillis())
                        admin.setRecordTime(System.currentTimeMillis() + 31536000000L);
                    else
                        admin.setRecordTime(admin.getRecordTime() + 31536000000L);
                }
                break;
            default:
                return;
        }
        baseMapper.updateById(admin);
    }

    public ApiResult<Integer> withdrawal(Integer userId, String token, Integer point, String zfbName, String zfbAccount) {
        ApiResult<Base> apiResult = checkUtils.checkToken(Arrays.asList(userId, token, point, zfbName, zfbAccount), userId, token, "");
        if (apiResult.getStatus() != 1)
            return new ApiResult<>(apiResult.getStatus(), apiResult.getMsg(), null);
        ApiResult<Integer> result = new ApiResult<>();
        int status = 0;
        String msg = "提现失败";
        try {
            Admin admin = baseMapper.selectById(userId);
            if (admin != null) {
                if (admin.getPoint() >= point) {
                    Integer withdrawalId = pointWithdrawalsService.add(admin, point, zfbName, zfbAccount);
                    pointRecordService.withdrawPoint(admin, point, zfbAccount + "(" + zfbName + ")", withdrawalId);
                    baseMapper.updateById(admin);
                    result.setData(admin.getPoint());
                    msg = "提现申请成功, 请耐心等待审核";
                    status = 1;
                } else {
                    msg = "积分不足";
                }
            } else msg = "用户不存在";
        } catch (Exception e) {
            e.printStackTrace();
        }
        result.setStatus(status);
        result.setMsg(msg);
        return result;
    }
}
